﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;

namespace CorpStoreServer
{
    public class PackageInfoGroupList
    {
        private int MAX_FEATURED_APPS = 4;

        public Dictionary<string, string> Settings { get; set; }
        public List<PackageInfoGroup> Groups { get; set; }
        private List<PackageInfo> featuredApps = new List<PackageInfo>();

        public PackageInfoGroupList()
        {
            Settings = new Dictionary<string,string>();
            Groups = new List<PackageInfoGroup>();
        }

        public List<PackageInfo> FeaturedApps
        {
            get
            {
                return featuredApps;
                //List<PackageInfo> apps = Groups.SelectMany(g => g.Applications).Where(a => a.IsFeatured).ToList<PackageInfo>();
                //apps.Sort((a1, a2) => a1.CreateDate.CompareTo(a2.CreateDate));
                //return apps;
            }
        }


        /// <summary>
        /// this function adds a new application to a new or existing application group,
        /// depending on the group the application belongs to.
        /// </summary>
        /// <param name="pkg"></param>
        /// <param name="logoFn"></param>
        /// <returns></returns>
        public bool AddApplication(PackageInfo app)
        {
            bool blnOK = false;
            PackageInfoGroup groupToAddTo = null;

            // attempt to find an existing application group with same group name of new app
            foreach (PackageInfoGroup group in Groups)
            {
                if (group.Name.Equals(app.GroupName, StringComparison.OrdinalIgnoreCase))
                {
                    groupToAddTo = group;
                    break;
                }
            }

            if (groupToAddTo == null)
            {
                // did not find existing group to add to - create new group 
                groupToAddTo = new PackageInfoGroup() { Name = app.GroupName, Description = "" };
                Groups.Add(groupToAddTo);
            }

            // now add this new app to our group
            groupToAddTo.AddApplication(app);

            // add a reference to this app to our sorted list as well
            AddFeaturedApp(app);

            return blnOK;
        }


        public void AddFeaturedApp(PackageInfo app)
        {
            if (featuredApps.Count < MAX_FEATURED_APPS)
            {
                app.IsFeatured = true;
                featuredApps.Add(app);
                featuredApps.Sort((a1, a2) => (a1.CreateDate.CompareTo(a2.CreateDate)));
            }
            else
            {
                // we have at least max_featured_apps apps already - check if create date of one at hand is later than latest in our list
                if (DateTime.Parse(app.CreateDate) > DateTime.Parse(featuredApps[0].CreateDate) || app.IsFeatured)
                {
                    // app at hand is later than earliest one OR it has been manually marked as featured - remove earliest 
                    featuredApps[0].IsFeatured = false;
                    featuredApps.RemoveAt(0);

                    // and replace with this one
                    app.IsFeatured = true;
                    featuredApps.Add(app);
                }
            }
        }


        /// <summary>
        /// sort all apps within groups by name and then sort all groups by their name 
        /// </summary>
        public void SortGroupsByName()
        {
            foreach (PackageInfoGroup group in Groups)
                group.SortApplicationsByName();

            Groups.Sort((g1, g2) =>
            {
                if (g1.Name.Equals("Other", StringComparison.OrdinalIgnoreCase))
                    return 1;
                else
                    return g1.Name.CompareTo(g2.Name);
            });
        }


        public PackageInfoGroupList Clone()
        {
            PackageInfoGroupList newList = new PackageInfoGroupList();

            // clone settings
            for (int i = 0; i < Settings.Count; i++)
                newList.Settings.Add(Settings.ElementAt(i).Key, Settings.ElementAt(i).Value);

            // clone groups
            for (int i = 0; i < Groups.Count; i++)
                newList.Groups.Add(Groups[i]);

            // clone featured apps
            for (int i = 0; i < FeaturedApps.Count; i++)
                newList.featuredApps.Add(featuredApps[i]);

            return newList;
        }

        //internal void MarkFeatured(int maxNumToFeature)
        //{
        //    // take items from end of recent apps list to get most recent ones
        //    for (int i = mostRecentApps.Count - 1; i >= Math.Max(0, mostRecentApps.Count - maxNumToFeature); i--)
        //    {
        //        PackageInfo app = mostRecentApps.Values[i];
        //        app.IsFeatured = true;
        //    }
        //}
    }
}
